package it.gat.webservice.resource.impl;

import java.sql.SQLException;

import org.restlet.resource.Delete;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.Put;
import org.restlet.resource.ServerResource;

import it.gat.dao.ClienteDAO;
import it.gat.dao.UtenteDAO;
import it.gat.model.Cliente;
import it.gat.util.dao.DAOFactory;
import it.gat.webservice.utils.Impostazioni;

public class ClienteResource extends ServerResource{
	
	@Post
	public Cliente insert(Cliente cliente) {
		DAOFactory daoFactory = DAOFactory.getDAOFactory(Integer.parseInt(Impostazioni.getProperty("DB_TYPE")));
		ClienteDAO clienteDAO = daoFactory.getClienteDAO();
		Cliente nuovoCliente = null;
		try {
			nuovoCliente = clienteDAO.insert(cliente);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return nuovoCliente;
	}

	@Get
	public Cliente retriveById() {
		DAOFactory daoFactory = DAOFactory.getDAOFactory(Integer.parseInt(Impostazioni.getProperty("DB_TYPE")));
		Cliente cliente;
		try {
			if (this.isNumeric(getRequestAttributes().get("id").toString()))
			{
				ClienteDAO clienteDAO = daoFactory.getClienteDAO();
				cliente = clienteDAO.retriveById(Integer.parseInt(getRequestAttributes().get("id").toString()));
			}
			else
			{
				UtenteDAO utenteDAO = daoFactory.getUtenteDAO();
				cliente = (Cliente) utenteDAO.retriveByNomeUtente(getRequestAttributes().get("id").toString());
			}
		} catch (NumberFormatException e) {
			return null;
		} catch (SQLException e) {
			return null;
		}
		return cliente;
	}

	@Put
	public void update(Cliente cliente) {
		DAOFactory daoFactory = DAOFactory.getDAOFactory(Integer.parseInt(Impostazioni.getProperty("DB_TYPE")));
		ClienteDAO clienteDAO = daoFactory.getClienteDAO();
		try {
			clienteDAO.update(cliente);
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	@Delete
	public void delete(Cliente cliente) {
		DAOFactory daoFactory = DAOFactory.getDAOFactory(Integer.parseInt(Impostazioni.getProperty("DB_TYPE")));
		ClienteDAO clienteDAO = daoFactory.getClienteDAO();
		try {
			clienteDAO.delete(Integer.parseInt(getRequestAttributes().get("id").toString()));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}
	
	public boolean isNumeric(String string){
		try{
			Integer.parseInt(string);
			return true;
		}
		catch (Exception ex)
		{
			return false;
		}
	}

}
